import { getProfileAPI, getUserAPI, loginAPI } from '@/api'
import router from '@/router'
import { getToken, setToken, removeToken } from '@/utils/auth'

const getDefaultState = () => {
  return {
    token: getToken(), // vuex 的 state 值，使用本地持久化的(刷新时，默认去本地取一个)
    name: '',
    avatar: '',
    userInfo: {} // 用户基本资料
  }
}

const state = getDefaultState()

const mutations = {
  RESET_STATE: (state) => {
    removeToken()
    Object.assign(state, getDefaultState())
  },
  SET_NAME: (state, name) => {
    state.name = name
  },
  SET_AVATAR: (state, avatar) => {
    state.avatar = avatar
  },

  // *********** token *************
  SET_TOKEN: (state, token) => {
    state.token = token
    setToken(token)
  },
  REMOVE_TOKEN: (state) => {
    state.token = ''
    removeToken()
  },

  // *********** userInfo *************
  SET_USERINFO: (state, userInfoObj) => {
    state.userInfo = {
      ...state.userInfo,
      ...userInfoObj
    }
  },
  REMOVE_USERINFO: (state) => {
    state.userInfo = ''
  }
}

const actions = {
  // 封装 -> 登录逻辑
  async loginActions({ commit }, userInfo) {
    const { data, message } = await loginAPI(userInfo)
    commit('SET_TOKEN', data)
    return message
  },

  // 封装 -> 获取用户基本信息逻辑
  async getProfileActions({ commit }) {
    const { data: infoObj, message } = await getProfileAPI()
    const { data: userObj } = await getUserAPI(infoObj.userId)
    commit('SET_USERINFO', { ...infoObj, ...userObj })
    return message
  },

  // 封装 —> 退出登录逻辑
  logoutActions({ commit }) {
    commit('RESET_STATE')
    router.replace(`/login?redirect=${router.currentRoute.fullPath}`)
  }
}

export default {
  namespaced: true,
  state,
  mutations,
  actions
}

